import React, { Component } from "react";
import { connect } from "react-redux";
import { Form, Switch, Icon, Checkbox, Popover, Button, Select, message } from "antd";
import constant from "../../../finance-setting/loan-setting/constant";
import { messages } from "share/common";
import Priority from "components/template/priority/priority";
import { Chooser } from "components/index";
import CompactInput from "components/compact-input";
import WrapFormItem from "components/wrap-form-item";
import httpFetch from "share/httpFetch";

const { Option } = Select;

@connect(mapStateToProps)
@Form.create()
class AccrualRule extends Component {
  state = {
    priority: {
      levelCode: "TENANT",
      levelOrgName: this.props.tenant.tenantName,
      levelOrgId: this.props.tenant.id,
    },
    saveLoading: false,
  };

  options = [
    {
      label: messages("finance-10.key1") /*审批中*/,
      value: 1002,
    },
    {
      label: messages("finance-10.key2") /*已通过*/,
      value: 1003,
    },
    {
      label: messages("finance-10.key3") /*审核通过*/,
      value: 1004,
    },
    {
      label: messages("finance-10.key4") /*待付款*/,
      value: 1007,
    },
  ];

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        const { record } = this.props.params,
          { close } = this.props;
        let attr = value.privateReportBillExpenseScopeList;
        if (attr.isAll === "1" && attr.privateReportBillExpenseScopeList.length === 0) {
          message.error(messages("finance-10.key5") /*请选择报销单费用行启用的费用类型*/);
          return -1;
        }
        value.privateReportBillExpenseScopeList = attr.privateReportBillExpenseScopeList;
        attr = value.vendorPayBillExpenseScopeList;
        if (attr.isAll === "1" && attr.vendorPayBillExpenseScopeList.length === 0) {
          message.error(messages("finance-10.key75") /*请选择对公支付单费用行启用的费用类型*/);
          return -1;
        }
        value.vendorPayBillExpenseScopeList = attr.vendorPayBillExpenseScopeList;
        attr = value.applicationBillExpenseScopeList;
        if (attr.isAll === "1" && attr.applicationBillExpenseScopeList.length === 0) {
          message.error(messages("finance-10.key6") /*请选择申请单明细启用的费用类型*/);
          return -1;
        }
        value.applicationBillExpenseScopeList = attr.applicationBillExpenseScopeList;
        this.setState({ saveLoading: true });
        httpFetch
          .post(`/api/accrued/expense/option`, Object.assign(record, value))
          .then(() => {
            message.success(messages("common.operate.success") /*操作成功*/);
            this.setState({ saveLoading: true });
            close(true);
          })
          .catch((e) => {
            this.setState({ saveLoading: false });
            message.error(e.response.data.message);
          });
      }
    });
  };

  render() {
    const { formItemLayout } = constant;
    const { saveLoading, priority } = this.state;
    const { close } = this.props;
    const { record } = this.props.params;
    const { getFieldDecorator } = this.props.form;
    return (
      <Form className={"new-form"}>
        <Form.Item label={messages("common.column.status") /*状态*/} {...formItemLayout}>
          {getFieldDecorator("enabled", {
            rules: [{ required: true }],
            valuePropName: "checked",
            initialValue: record.hasOwnProperty("id") ? record.enabled : true,
          })(<Switch />)}
        </Form.Item>
        <Priority
          top="TENANT"
          showSetOfBooks
          disabledTop
          defaultValue={priority}
          showCompanyComponent={false}
          formItemLayout={formItemLayout}
          single={false}
          showCompany={false}
        />
        <h3 className="sub-title">{messages("finance-10.key7") /*自动预提数据设置*/}</h3>
        <div className={"third-title"} style={{ marginBottom: "12px" }}>
          {messages("finance-10.key8") /*报销单费用行*/}
        </div>
        <Form.Item
          label={
            <span style={{ paddingLeft: "12px" }}>
              <Icon style={{ transform: "rotateY(180deg)" }} type="enter" className="rotate-icon" />
              {messages("finance-10.key9") /*单据状态*/}
            </span>
          }
        >
          {getFieldDecorator("privateReportBillStatusList", {
            initialValue: record.hasOwnProperty("id") ? record.privateReportBillStatusList : [],
          })(<Checkbox.Group options={this.options} />)}
        </Form.Item>
        <Form.Item
          label={
            <span style={{ paddingLeft: "12px" }}>
              <Icon style={{ transform: "rotateY(180deg)" }} type="enter" className="rotate-icon" />
              {messages("finance-10.key10") /*单据范围*/}
            </span>
          }
        >
          {getFieldDecorator("privateReportBillFormScopeList", {
            initialValue: record.hasOwnProperty("id")
              ? record.privateReportBillFormScopeList.map((item) => ({ formOID: item }))
              : [],
          })(
            <Chooser
              type={"tenant_forms"}
              listExtraParams={{ entityTypeList: [1002] }}
              labelKey="formName"
              valueKey="formOID"
              onlyNeed="formOID"
              showNumber
            />
          )}
        </Form.Item>
        <Form.Item
          label={
            <span style={{ paddingLeft: "12px" }}>
              <Icon style={{ transform: "rotateY(180deg)" }} type="enter" className="rotate-icon" />
              {messages("finance-10.key11") /*启用的费用类型*/}
            </span>
          }
        >
          {getFieldDecorator("privateReportBillExpenseScopeList", {
            rules: [{ required: true }],
            initialValue: record.hasOwnProperty("id")
              ? {
                  isAll: record.privateReportBillExpenseScopeList.length > 0 ? "1" : "0",
                  privateReportBillExpenseScopeList: record.privateReportBillExpenseScopeList,
                }
              : {
                  isAll: "0",
                  privateReportBillExpenseScopeList: [],
                },
          })(
            <WrapFormItem>
              {(onchange, value) => (
                <CompactInput>
                  <Select
                    value={value.isAll}
                    onChange={(value) =>
                      onchange({
                        isAll: value,
                        privateReportBillExpenseScopeList: [],
                      })
                    }
                  >
                    <Option key={"0"}>{messages("common.all") /*全部*/}</Option>
                    <Option key={"1"}>{messages("finance-10.key12") /*部分*/}</Option>
                  </Select>
                  <Chooser
                    disabled={value.isAll === "0"}
                    type={"available_expense"}
                    labelKey={"name"}
                    valueKey={"expenseTypeOID"}
                    listExtraParams={{
                      levelCode: "ALL",
                    }}
                    showNumber
                    value={(value.privateReportBillExpenseScopeList || []).map((item) => ({ expenseTypeOID: item }))}
                    onChange={(res) =>
                      onchange({ privateReportBillExpenseScopeList: res.map((item) => item.expenseTypeOID) })
                    }
                  />
                </CompactInput>
              )}
            </WrapFormItem>
          )}
        </Form.Item>
        <div className={"third-title"} style={{ margin: "32px 0 12px" }}>
          {messages("finance-10.key13") /*对公支付单费用行*/}
        </div>
        <Form.Item
          label={
            <span style={{ paddingLeft: "12px" }}>
              <Icon style={{ transform: "rotateY(180deg)" }} type="enter" className="rotate-icon" />
              {messages("finance-10.key9") /*单据状态*/}
            </span>
          }
        >
          {getFieldDecorator("vendorPayBillStatusList", {
            initialValue: record.hasOwnProperty("id") ? record.vendorPayBillStatusList : [],
          })(<Checkbox.Group options={this.options} />)}
        </Form.Item>
        <Form.Item
          label={
            <span style={{ paddingLeft: "12px" }}>
              <Icon style={{ transform: "rotateY(180deg)" }} type="enter" className="rotate-icon" />
              {messages("finance-10.key10") /*单据范围*/}
            </span>
          }
        >
          {getFieldDecorator("vendorPayBillFormScopeList", {
            initialValue: record.hasOwnProperty("id")
              ? record.vendorPayBillFormScopeList.map((item) => ({ formOID: item }))
              : [],
          })(
            <Chooser
              type={"tenant_forms"}
              listExtraParams={{ entityTypeList: [3004] }}
              labelKey="formName"
              valueKey="formOID"
              onlyNeed="formOID"
              showNumber
            />
          )}
        </Form.Item>
        <Form.Item
          label={
            <span style={{ paddingLeft: "12px" }}>
              <Icon style={{ transform: "rotateY(180deg)" }} type="enter" className="rotate-icon" />
              {messages("finance-10.key11") /*启用的费用类型*/}
            </span>
          }
        >
          {getFieldDecorator("vendorPayBillExpenseScopeList", {
            rules: [{ required: true }],
            initialValue: record.hasOwnProperty("id")
              ? {
                  isAll: record.vendorPayBillExpenseScopeList.length > 0 ? "1" : "0",
                  vendorPayBillExpenseScopeList: record.vendorPayBillExpenseScopeList,
                }
              : {
                  isAll: "0",
                  vendorPayBillExpenseScopeList: [],
                },
          })(
            <WrapFormItem>
              {(onchange, value) => (
                <CompactInput>
                  <Select
                    value={value.isAll}
                    onChange={(value) =>
                      onchange({
                        isAll: value,
                        vendorPayBillExpenseScopeList: [],
                      })
                    }
                  >
                    <Option key={"0"}>{messages("common.all") /*全部*/}</Option>
                    <Option key={"1"}>{messages("finance-10.key12") /*部分*/}</Option>
                  </Select>
                  <Chooser
                    disabled={value.isAll === "0"}
                    type={"available_expense"}
                    labelKey={"name"}
                    valueKey={"expenseTypeOID"}
                    listExtraParams={{
                      levelCode: "ALL",
                    }}
                    showNumber
                    value={(value.vendorPayBillExpenseScopeList || []).map((item) => ({ expenseTypeOID: item }))}
                    onChange={(res) =>
                      onchange({ vendorPayBillExpenseScopeList: res.map((item) => item.expenseTypeOID) })
                    }
                  />
                </CompactInput>
              )}
            </WrapFormItem>
          )}
        </Form.Item>
        <div className={"third-title"} style={{ margin: "32px 0 12px" }}>
          {messages("finance-10.key14") /*申请单明细*/}
        </div>
        <Form.Item
          label={
            <span style={{ paddingLeft: "12px" }}>
              <Icon style={{ transform: "rotateY(180deg)" }} type="enter" className="rotate-icon" />
              {messages("finance-10.key9") /*单据状态*/}
            </span>
          }
        >
          {getFieldDecorator("applicationBillStatusList", {
            initialValue: record.hasOwnProperty("id") ? record.applicationBillStatusList : [],
          })(
            <Checkbox.Group
              options={[
                {
                  label: (
                    <Popover
                      content={
                        messages(
                          "finance-10.key15"
                        ) /*申请单未开启预算占用，只有单据状态为“已通过”的申请单会参与预提，建议配置只允许报销一次，防止报销后重复预提*/
                      }
                    >
                      {messages("finance-10.key16") /*已通过（不占预算）*/}
                      <Icon type="info-circle-o" style={{ marginLeft: "5px", fontWeight: 600 }} />
                    </Popover>
                  ),
                  value: 1000,
                },
                {
                  label: (
                    <Popover
                      content={
                        messages(
                          "finance-10.key17"
                        ) /*申请单开启了预算占用，报销时会释放预算，只有单据状态为“已通过”的申请单会参与预提且可预提金额=申请单剩余预算金额*/
                      }
                    >
                      {messages("finance-10.key18") /*已通过且有剩余预算*/}
                      <Icon type="info-circle-o" style={{ marginLeft: "5px", fontWeight: 600 }} />
                    </Popover>
                  ),
                  value: 1001,
                },
              ]}
            />
          )}
        </Form.Item>
        <Form.Item
          label={
            <span style={{ paddingLeft: "12px" }}>
              <Icon style={{ transform: "rotateY(180deg)" }} type="enter" className="rotate-icon" />
              {messages("finance-10.key10") /*单据范围*/}
            </span>
          }
        >
          {getFieldDecorator("applicationBillFormScopeList", {
            initialValue: record.hasOwnProperty("id")
              ? record.applicationBillFormScopeList.map((item) => ({ formOID: item }))
              : [],
          })(
            <Chooser
              type={"tenant_forms"}
              listExtraParams={{ entityTypeList: [1001] }}
              labelKey="formName"
              valueKey="formOID"
              onlyNeed="formOID"
              showNumber
            />
          )}
        </Form.Item>
        <Form.Item
          label={
            <span style={{ paddingLeft: "12px" }}>
              <Icon style={{ transform: "rotateY(180deg)" }} type="enter" className="rotate-icon" />
              {messages("finance-10.key11") /*启用的费用类型*/}
            </span>
          }
        >
          {getFieldDecorator("applicationBillExpenseScopeList", {
            rules: [{ required: true }],
            initialValue: record.hasOwnProperty("id")
              ? {
                  isAll: record.applicationBillExpenseScopeList.length > 0 ? "1" : "0",
                  applicationBillExpenseScopeList: record.applicationBillExpenseScopeList,
                }
              : {
                  isAll: "0",
                  applicationBillExpenseScopeList: [],
                },
          })(
            <WrapFormItem>
              {(onchange, value) => (
                <CompactInput>
                  <Select
                    value={value.isAll}
                    onChange={(value) =>
                      onchange({
                        isAll: value,
                        applicationBillExpenseScopeList: [],
                      })
                    }
                  >
                    <Option key={"0"}>{messages("common.all") /*全部*/}</Option>
                    <Option key={"1"}>{messages("finance-10.key12") /*部分*/}</Option>
                  </Select>
                  <Chooser
                    disabled={value.isAll === "0"}
                    type={"available_expense"}
                    labelKey={"name"}
                    valueKey={"expenseTypeOID"}
                    listExtraParams={{
                      levelCode: "ALL",
                    }}
                    showNumber
                    value={(value.applicationBillExpenseScopeList || []).map((item) => ({ expenseTypeOID: item }))}
                    onChange={(res) =>
                      onchange({ applicationBillExpenseScopeList: res.map((item) => item.expenseTypeOID) })
                    }
                  />
                </CompactInput>
              )}
            </WrapFormItem>
          )}
        </Form.Item>
        <h3 className="sub-title">{messages("finance-10.key19") /*预提复核设置*/}</h3>
        <Form.Item label={messages("finance-10.key20") /*是否需要复核*/} {...formItemLayout}>
          {getFieldDecorator("needReview", {
            rules: [{ required: true }],
            valuePropName: "checked",
            initialValue: record.hasOwnProperty("id") ? record.needReview : false,
          })(
            <Checkbox style={{ color: "#6c788c" }}>
              ({messages("finance-10.key21") /*开启后，自动预提数据需要经过复核*/})
            </Checkbox>
          )}
        </Form.Item>
        <div className="slide-footer">
          <Button type="primary" onClick={this.handleSave} loading={saveLoading}>
            {messages("common.ok") /*确定*/}
          </Button>
          <Button onClick={() => close()}>{messages("common.cancel") /*取消*/}</Button>
        </div>
      </Form>
    );
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  };
}

export default AccrualRule;
